



//
//  CPJNetworkManager+Extension.swift
//  Sina
//
//  Created by YYY on 2017/7/31.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

extension CPJNetworkManager
{
    func statusList(since_id: Int64 = 0,max_id: Int64 = 0,completion: @escaping (_ list: [[String: AnyObject]]?,_ isOK: Bool) -> ())
    {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id": "\(since_id)",
            "max_id": "\(max_id>0 ? max_id-1 : 0)"]
        
        appendToken(URLString: urlString, parameters: params as [String : AnyObject]) { (jsonData, isSuccess) in
            let dict = jsonData as? [String: AnyObject]
            let result = dict?["statuses"] as? [[String: AnyObject]]
            completion(result,isSuccess)
        }
    }
}

extension CPJNetworkManager
{
    //未读的微博数据
    func loadUnReadData(completion: @escaping(_ count: Int)->())
    {
        guard let uid = userAccount.uid else
        {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        
        appendToken(URLString: urlString, parameters: params as [String: AnyObject]) { (jsonData, isSuccess) in
            
            //print(jsonData)
            
            let dict = jsonData as? [String: AnyObject]
            
    
            let unReadCcont = dict?["status"] as? Int
            completion(unReadCcont ?? 0)
        }
    }
}

//发布微博
extension CPJNetworkManager
{
    
    /// 发布微博
    ///
    /// - Parameters:
    ///   - text: 发布的文本
    ///   - image: 发布的图片，为nil，表示发布纯文本微博
    ///   - completion: 完成回调
    func postWeibo(text: String,image: UIImage?, completion: @escaping(_ resultDict: [String: AnyObject]?,_ isSuccess: Bool)->())
    {
        //地址url
        let urlString: String
        //根据是否有图像，选择不同的URL地址
        if image == nil
        {
            //纯文本微博
            urlString = "https://api.weibo.com/2/statuses/update.json"
        }
        else
        {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        
        //参数字典
        let params = ["status": text]
        
        //如果image不为nil，需要name和data
        var name: String?
        var data: Data?
        if image != nil
        {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
            //上传带有图片的微博
            
        }
        appendToken(method: .POST, URLString: urlString, parameters: params as [String: AnyObject], name: name, data: data) { (jsonDict, isSuccess) in
            completion(jsonDict as? [String: AnyObject],isSuccess)
        }
    }
}

extension CPJNetworkManager
{
    //加载用户信息
    func loadUserInfo(completion: @escaping(_ userInfoDict: [String: AnyObject])->())
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userAccount.uid else
        {
            return
        }
        let param = ["uid": uid] as [String: AnyObject]
        
        appendToken(URLString: urlString, parameters: param) { (json, isSuccess) in
            let tempJson = (json as? [String: AnyObject]) ?? [:]
            completion(tempJson)
        }
    }
}

// MARK: - 根据授权码获取AccessToken
extension CPJNetworkManager
{
    func loadAccessToken(code: String,completion:
        @escaping(_ isSuccess: Bool)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": SinaAppKey,
                      "client_secret": SinaAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": SinaAppRedirect_uri]
        
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject])
        { (json, success) in
            
            let jsonDict = json as? [String: AnyObject] ?? [:]
            
            self.userAccount.yy_modelSet(with: jsonDict)
        

            self.loadUserInfo(completion: { (userInfoDict) in
                
                self.userAccount.yy_modelSet(with: userInfoDict)
                
                self.userAccount.saveAccount()
                
                completion(success)
                
            })

        }
    }
}
